package com.rankeiot.compiler;

import com.caoccao.javet.exceptions.JavetException;
import com.caoccao.javet.values.primitive.V8ValueString;
import com.caoccao.javet.values.reference.V8ValueGlobalObject;
import com.caoccao.javet.values.reference.V8ValuePromise;

import java.io.IOException;

/**
 * JS代码压缩
 */
public class UglifyCompiler extends V8Compiler{
    private UglifyCompiler() {
       // super("/terser.min.js","function compile(source){return Terser.minify(source,{compress:{drop_console:true,drop_debugger:true},parse:{module:true},rename:true,output:{ascii_only:true}}).then(r=>code=r.code);}");
        super("/uglifyjs.js", "function compile(source){ return UglifyJS.minify(source,{compress:{drop_console:true,drop_debugger:true},parse:{module:true},rename:true,output:{ascii_only:true},toplevel:true}).code};");
    }
    private static UglifyCompiler instance;

    public static UglifyCompiler getInstance() {
        if(instance==null){
            instance=new UglifyCompiler();
        }
        return instance;
    }
    @Override
    public String compile(String source) {
        try {
            V8ValueString obj = runtime.getGlobalObject().invoke("compile",source);
            return obj.getValue();
        } catch (JavetException e) {
            throw new RuntimeException(e);
        }
    }
    public static void closeInstance(){
        if(instance!=null){
            try {
                instance.close();
                instance=null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
